package org.bling.star.server.utils;


import org.bling.star.common.connect.CommandStreamKey;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.security.*;
import java.util.Random;
import java.util.UUID;

public class GeneratorUtils {
    public static CommandStreamKey generateKey() {
        return new CommandStreamKey(generateTalkingName(),50,true);
    }

    private static final String[] THEMES = {"星际", "梦幻", "知识", "幻影", "时光", "彩虹", "秘境"};
    private static final String[] ROOM_SUFFIXES = {"阁", "屋", "林", "迷宫", "回廊", "乐园", "队"};

    public static String generateTalkingName() {
        // 生成一个随机的UUID
        UUID uuid = UUID.randomUUID();
        // 将UUID转换为字符串形式
        String randomID = uuid.toString();
        Random random = new Random();
        String theme = THEMES[random.nextInt(THEMES.length)];
        String suffix = ROOM_SUFFIXES[random.nextInt(ROOM_SUFFIXES.length)];
        return theme + suffix + randomID;
    }

    public static byte[] generatorRSAMessage() {
        //钥匙要在连接创建的时候发放
        try {
            // 创建KeyPairGenerator实例
            KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");

            // 初始化密钥生成器，指定密钥长度
            keyGen.initialize(2048);

            // 生成密钥对
            KeyPair keyPair = keyGen.generateKeyPair();

            // 获取公钥和私钥
            PublicKey publicKey = keyPair.getPublic();
            PrivateKey privateKey = keyPair.getPrivate();
            // 原始数据
            byte[] data = "Hello, this is a secret message!".getBytes();

            // 加密数据
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] encryptedData = cipher.doFinal(data);

            // 解密数据
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] decryptedData = cipher.doFinal(encryptedData);

            // 输出结果
            System.out.println("原始数据: " + new String(data));
            System.out.println("加密后的数据: " + new String(encryptedData)); // 注意，加密后的数据可能无法直接显示为可读文本
            System.out.println("解密后的数据: " + new String(decryptedData));
            // 打印公钥和私钥的信息
            System.out.println("公钥: " + publicKey);
            System.out.println("私钥: " + privateKey);
            return encryptedData;
        } catch (NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException e) {
            e.printStackTrace();
            return null;
        }
    }
}
